<?php
/**
 * YunSms.php
 * 云短信网验证码
 * 
 * @author  王中艺 <wangzy_smile@qq.com>
 * @date    2018-06-30 14:57:08
 */

namespace App\Utils\Sms;
use App\Exceptions\NormalException;
use App\Utils\Sms;
use App\Utils\Log;

class YunSms extends Sms {

    public $api = 'http://http.yunsms.cn/tx/';

    const ERROR_CODE = [
        '101' => '验证失败',
        '102' => '短信不足',
        '103' => '操作失败',
        '104' => '非法字符',
        '105' => '内容过多',
        '106' => '号码过多',
        '108' => '号码内容为空',
        '107' => '频率过快',
        '109' => '账号冻结',
        '110' => '禁止频繁单条发送',
        '111' => '系统暂定发送',
        '112' => '有错误号码',
        '113' => '定时时间不对',
        '114' => '账号被锁，10分钟后登录',
        '115' => '连接失败',
        '116' => '禁止接口发送',
        '117' => '绑定IP不正确',
        '120' => '系统升级'
    ];

    /**
     * 发送
     * @param   $mobile 手机号
     * @param   $content 发送内容
     * @return  code [<description>]
     */
    protected function toSend($mobile, $content){
        $info = config('sms.yunsms');
        $data = [
            'uid' => $info['uid'],
            'pwd' => strtolower(md5($info['pwd'])),
            'mobile' => $mobile,
            'content' => iconv('utf-8', 'gbk', $content),
            'time' => '',
            'mid' => ''
        ];

        $result = $this->_send($this->api, $data);

        if($result != 100){
            if(isset(self::ERROR_CODE[$result])){
                $result .= '_'.self::ERROR_CODE[$result];
            }

            //日志添加
            Log::getInstance('file')->put('sms_error', [
                'driver' => 'yumsms',
                'mobile' => $mobile,
                'content' => $content,
                'result' => $result
            ]);

            throw new NormalException(611, $result);
        }

        return true;
    }

    /**
     * 执行发送
     * @param   $url
     * @param   $data
     * @return  code [<description>]
     */
    private function _send($url, $data='') {
        $post='';
        $row = parse_url($url);
        $host = $row['host'];
        $port = isset($row['port']) ? $row['port']:80;
        $file = $row['path'];
        foreach ($data as $k => $v) {
            $post .= rawurlencode($k)."=".rawurlencode($v)."&"; //转URL标准码
        }
        $post = substr( $post , 0 , -1 );
        $len = strlen($post);
         
        $fp = stream_socket_client("tcp://".$host.":".$port, $errno, $errstr, 10);
        
        if (!$fp) {
            return "$errstr ($errno)\n";
        } else {
            $receive = '';
            $out = "POST $file HTTP/1.0\r\n";
            $out .= "Host: $host\r\n";
            $out .= "Content-type: application/x-www-form-urlencoded\r\n";
            $out .= "Connection: Close\r\n";
            $out .= "Content-Length: $len\r\n\r\n";
            $out .= $post;      
            fwrite($fp, $out);
            while (!feof($fp)) {
                $receive .= fgets($fp, 128);
            }
            fclose($fp);
            $receive = explode("\r\n\r\n",$receive);
            unset($receive[0]);
            return implode("",$receive);
        }
    }
} 
